import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { AsyncTaskHandler } from '@/utils/asyncTaskHandler'
import { reqLogin, reqRegister, reqLogout } from '@/api/login'
import { useRouter } from 'vue-router'
import { secureStorage } from '@/utils/secureStorage'

// 用户信息类型定义
interface User {
  id: number
  userName?: string
  nickname: string
  avatar?: string
}

// 登录响应数据类型
interface LoginResponse {
  avatar: string
  id: number
  nickname: string
  token: string
  userName: string
}
interface RegisterCredentials {
  username: string
  password: string
  email: string
}
// 登录凭证类型
interface LoginCredentials {
  username: string
  password: string
  rememberMe?: boolean
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    // 用户基本信息
    user: null as User | null,

    // JWT token (建议通过 HttpOnly Cookie 存储)
    token: null as string | null,

    // 登录状态
    isLoggedIn: false,

    // 加载状态
    isLoading: false,

    // 错误信息
    error: null as string | null,
  }),
  persist: true, // 持久化存储

  getters: {
    // 安全获取用户信息（返回克隆对象）
    currentUser: (state) => (state.user ? { ...state.user } : null),

    // 获取用户头像（带默认值）
    userAvatar: (state) => state.user?.avatar || '',

    // 是否已认证
    isAuthenticated: (state) => state.isLoggedIn,

    // 用户的id
    userId: (state) => state.user?.id || null,

    // 获取显示名称（优先昵称）
    displayName: (state) => state.user?.nickname || state.user?.userName || '',
  },

  actions: {
    // 异步登录方法
    async login(credentials: LoginCredentials) {
      try {
        this.isLoading = true
        this.error = null

        // 调用你的异步请求方法
        const res = await AsyncTaskHandler.handleSingleTask(
          reqLogin({
            username: credentials.username,
            password: credentials.password,
          }),
        )

        if (res.code === 0) {
          // 类型断言确保数据结构正确
          const response = res.data as LoginResponse

          // 正确的状态更新
          this.user = {
            id: response.id,
            userName: '',
            nickname: response.nickname,
            avatar: response.avatar || '',
          }
          this.isLoggedIn = true
          // 安全存储
          secureStorage.set('token', response.token)
          return {
            states: true,
            message: '登录成功',
          } // 返回成功状态
        } else {
          this.error = res.msg
          return false
        }
      } catch (err) {
        const message = (err as Error).message || '登录请求异常'
        this.error = message
        return {
          states: false,
          message: message,
        }
      } finally {
        this.isLoading = false
      }
    },
    async register(credentials: RegisterCredentials) {
      try {
        this.isLoading = true
        this.error = null

        // 基础客户端验证
        if (!credentials.username || !credentials.password || !credentials.email) {
          throw new Error('请填写所有必填字段')
        }

        // 调用注册API
        const res = await AsyncTaskHandler.handleSingleTask(
          reqRegister({
            username: credentials.username,
            password: credentials.password,
            email: credentials.email,
          }),
        )

        if (res.code == 0) {
          // 类型断言确保数据结构正确
          const response = res.data as LoginResponse

          // 正确的状态更新
          this.user = {
            id: response.id,
            userName: '',
            nickname: response.nickname,
            avatar: response.avatar || '',
          }

          this.isLoggedIn = true
          // 安全存储
          secureStorage.set('token', response.token)
          return {
            states: true,
            message: '注册成功',
          } // 返回成功状态
        } else {
          this.error = res.msg
          return false
        }
      } catch (err) {
        const message = (err as Error).message || '注册请求异常'
        this.error = message
        return {
          states: false,
          message: message,
        }
      } finally {
        this.isLoading = false
      }
    },
    // 登出方法
    async logout() {
      try {
        // 调用后端登出接口
        let res = await reqLogout()
        return true
      } finally {
        // 清除所有状态
        this.$reset()

        // 清除安全存储
        secureStorage.remove('token')
      }
    },
    // 自动登录校验
    async checkAuthStatus() {
      if (!this.token) return false

      try {
        // 实际替换为 token 验证接口
        const response = await fetch('/api/check-auth', {
          headers: {
            Authorization: `Bearer ${this.token}`,
          },
        })

        this.isLoggedIn = response.ok
        return this.isLoggedIn
      } catch {
        this.isLoggedIn = false
        return false
      }
    },
    // 更新成功后重新设置nickname 和avatar
    updateUserInfo(user: Partial<User>) {
      if (user.nickname) this.user!.nickname = user.nickname
      if (user.avatar) this.user!.avatar = user.avatar
    },
  },
})
